import { SetupContext, defineComponent, ref, watch } from 'vue';
import { SearchBoxProps, searchBoxProps } from './search-box.props';
import SearchBoxContainer from './components/search-box-container.component';
import './search-box.css';

declare const Highlight: any;

export default defineComponent({
    name: 'FSearchBox',
    props: searchBoxProps,
    emits: ['update:modelValue', 'change', 'clickButton'],
    setup(props: SearchBoxProps, context: SetupContext) {
        const recommendedData = ref(props.recommendedData);
        const buttonEditRef = ref<any>();
        const searchBoxContainerRef = ref<any>();
        const filterBoxPlaceholder = ref('请输入关键词');
        const searchIconContent = ref('<i class="f-icon f-icon-search"></i>');
        const searchValue = ref(props.modelValue);

        watch(searchValue, (searchingText: string) => {
            searchBoxContainerRef.value?.search(searchingText);
            context.emit('update:modelValue', searchingText);
        });

        watch(
            () => props.modelValue,
            (value: string) => {
                searchValue.value = value;
            }
        );

        function onConfirmResult(searchResult: string) {
            buttonEditRef.value.commitValue(searchResult);
        }

        function onFilterValueChange(newValue: string) {
            context.emit('change', newValue);
        }
        function onButtonClicked(newValue) {
            context.emit('clickButton', newValue);
        }
        return () => {
            return (
                <div>
                    <f-button-edit
                        ref={buttonEditRef}
                        button-content={searchIconContent.value}
                        placeholder={filterBoxPlaceholder.value}
                        onChange={onFilterValueChange}
                        enable-clear={true}
                        button-behavior="Execute"
                        v-model={searchValue.value}
                        popup-host={props.popupHost}
                        popup-right-boundary={props.popupRightBoundary}
                        popup-offset-x={props.popupOffsetX}
                        popup-on-input={true}
                        popup-on-focus={true}
                        onClickButton={onButtonClicked}>
                        <SearchBoxContainer
                            ref={searchBoxContainerRef}
                            data={recommendedData.value}
                            onConfirmResult={onConfirmResult}></SearchBoxContainer>
                    </f-button-edit>
                </div>
            );
        };
    }
});
